package Servicios;

import DAO.DAOAsignaturaOfertaAcademica;
import DAO.DAOProgramaEducativo;
import DAO.DAORelacionAlumnoProgramaEducativo;
import Dominio.ProgramaEducativo;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class GestorDeProgramasEducativos extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String operacion = request.getParameter("operacion");

        if (operacion.equalsIgnoreCase("registraPE")) {
            registraPE(request, response);
        } else {
            if (operacion.equalsIgnoreCase("eliminaPE")) {
                eliminaPE(request, response);
            } else {
                if (operacion.equalsIgnoreCase("buscarPES")) {
                    buscarTodosLosProgramasEducativos(request, response);
                } else {
                    String resp = "El servicio solicitado no existe.";
                    PrintWriter out = response.getWriter();
                    out.println(resp);
                }
            }
        }


    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void registraPE(HttpServletRequest request, HttpServletResponse response) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        HashMap<String, String> parametros = new HashMap<String, String>();
        try {
            List items = upload.parseRequest(request);
            File fichero = new File("a.xls");
            for (Object item : items) {
                FileItem uploaded = (FileItem) item;
                if (!uploaded.isFormField()) {
                    fichero = new File("/tmp", uploaded.getName());
                    uploaded.write(fichero);
                } else {
                    String key;
                    key = uploaded.getFieldName();
                    String valor = uploaded.getString();
                    parametros.put(key, valor);
                }
            }
            System.out.println(fichero.getAbsolutePath());
            System.out.println(parametros);
            response.getWriter().println(fichero.getAbsolutePath());
        } catch (Exception ex) {
            Logger.getLogger(GestorDeProgramasEducativos.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private void eliminaPE(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
            String clavePEIntegerCadena = request.getParameter("claveProgramaEducativo");
            DAOAsignaturaOfertaAcademica daoOferta = new DAOAsignaturaOfertaAcademica();
            DAOProgramaEducativo daoPE = new DAOProgramaEducativo();
           
            int claveIntPE = Integer.parseInt(clavePEIntegerCadena);
            System.out.println("Clave del programa educativo: " + claveIntPE);
            String nombrePE = daoPE.obtenerabreviaturaDePE(claveIntPE);
            DAORelacionAlumnoProgramaEducativo daorelPE = new DAORelacionAlumnoProgramaEducativo();
            if (!daoOferta.existeAsignaturasDeOferta(nombrePE)) {
                if (!daorelPE.existeAlumnoRelacionadoConPE(claveIntPE)) {
                    if (clavePEIntegerCadena != null) {

                        int claveProgramaEducativo = Integer.parseInt(clavePEIntegerCadena);

                        DAOProgramaEducativo daoProgramaEducativo = new DAOProgramaEducativo();
                        daoProgramaEducativo.eliminarProgramaEducativo(claveProgramaEducativo);
                        daoProgramaEducativo.cerrarconexionAProgramas();                                                

                        out.println("Programa educativo eliminado con exito");
                    } else {
                        out.println("Ocurrio un error al procesar la peticion");
                    }
                }
                else{
                out.println("El programa educativo no se puede eliminar debido a que ya existen alumnos registrados ahi.");
                }

            } else {
                out.println("El programa educativo no se puede eliminar debido a que existe una oferta academica registrada. Elimine la oferta academica primero.");
            }


        } catch (IOException ex) {
            Logger.getLogger(GestorDeProgramasEducativos.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    private void buscarTodosLosProgramasEducativos(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
            DAOProgramaEducativo daoProgramaEducativo = new DAOProgramaEducativo();
            ArrayList<ProgramaEducativo> listaProgramasEducativos = daoProgramaEducativo.listarProgramas();
            daoProgramaEducativo.cerrarconexionAProgramas();
            String respuesta = "<table border=\"1\">"
                    + "    <th>"
                    + "        Programa educativo"
                    + "    </th>";
            for (int i = 0; i < listaProgramasEducativos.size(); i++) {
                ProgramaEducativo programaEducativo = listaProgramasEducativos.get(i);

                respuesta += "    <tr>"
                        + "        <td>"
                        + "            " + programaEducativo.getNombre()
                        + "        </td>"
                        + "        <td>"
                        + "            <input type=\"button\" value=\"Eliminar\" onClick=\"eliminarProgramaEducativo(" + programaEducativo.getCvePrograma() + ")\"/>"
                        + "        </td>"
                        + "    </tr>";

            }
            respuesta += "</table>";
            if (listaProgramasEducativos.isEmpty()) {
                out.println("No se encontraron programas educativos");
            } else {
                out.println(respuesta);
            }
        } catch (IOException ex) {
            Logger.getLogger(GestorDeProgramasEducativos.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }
}
